<template>
  <div class="container">
    <div class="login-wrapper">
      <div class="header">Login</div>
      <div class="form-wrapper">
        <input
          type="text"
          name="username"
          placeholder="username"
          class="input-item"
          v-model="user.username"
        />
        <input
          type="password"
          name="password"
          placeholder="password"
          class="input-item"
          v-model="user.password"
        />
        <div class="btn" @click="login()">Login</div>
        <div class="btn" @click="register()">Register</div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'Login',
}
</script>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { ref } from 'vue'
import { type IUser } from '../pages/Register.vue'
import { fa } from 'element-plus/es/locales.mjs'

const user = ref<IUser>({
  id: 0,
  username: '',
  password: '',
})

const users = (JSON.parse(localStorage.getItem('users') as string) as IUser[]) || [] // 获取本地存储的用户信息

const router = useRouter() // 使用路由
const login = () => {
  // 过滤用户信息
  const loginUser =
    users.filter(
      (item) => item.username === user.value.username && item.password === user.value.password,
    )[0] || user

  // 点击登录
  if (loginUser.id > 0) {
    // 登录成功
    localStorage.setItem('user', JSON.stringify(loginUser))
    localStorage.setItem('time', new Date().toLocaleString())
    setInterval(
      () => {
        router.push({ name: 'home' })
      },
      Math.random() * 500 + 500,
    )
  } else {
    alert('用户名或密码错误')
  }
}
const register = () => {
  // 点击跳转到注册页面
  router.push({ name: 'Register' })
}
</script>

<style scoped>
html {
  height: 100%;
}
body {
  height: 100%;
}
.container {
  /* margin-top: 5%; */
  height: 980px;
  width: 100%;
  background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);
}
.login-wrapper {
  background-color: #fff;
  width: 358px;
  height: 588px;
  border-radius: 15px;
  padding: 0 50px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.header {
  font-size: 38px;
  font-weight: bold;
  text-align: center;
  line-height: 200px;
}
.input-item {
  display: block;
  width: 100%;
  margin-bottom: 20px;
  border: 0;
  padding: 10px;
  border-bottom: 1px solid rgb(128, 125, 125);
  font-size: 15px;
  outline: none;
}
.input-item:placeholder {
  text-transform: uppercase;
}
.btn {
  text-align: center;
  padding: 10px;
  margin: 0 auto;
  width: 100%;
  margin-top: 40px;
  background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
  color: #fff;
}
.msg {
  text-align: center;
  line-height: 88px;
}
a {
  text-decoration-line: none;
  color: #abc1ee;
}
</style>
